package com.easy;

import java.util.*;

/**
 * Created by Lxk on 2019/5/17.
 */
public class Solution107 {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        Stack<List<Integer>> stack = new Stack<>();
        List<List<Integer>> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode levelEnd = root;
        TreeNode lastNode = root;
        queue.offer(root);
        List<Integer> level = new ArrayList<>();
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(cur.left != null){
                queue.offer(cur.left);
                lastNode = cur.left;
            }
            if(cur.right != null){
                queue.offer(cur.right);
                lastNode = cur.right;
            }
            level.add(cur.val);
            if(cur == levelEnd){
                levelEnd = lastNode;
                stack.add(level);
                level = new ArrayList<>();
            }
        }
        while(!stack.isEmpty()){
            res.add(stack.pop());
        }
        return res;
    }

}
